using System;
using System.Collections.Generic;

namespace Activa.ProMesh
{
    public class CSSessionDataProvider : ISessionLoggingProvider
    {
        public string CreateSession(string httpReferer, string httpRemoteAddress, string httpUserAgent)
        {
            Session session = Session.New();

            if (httpReferer == null)
                httpReferer = "";
            if (httpUserAgent == null)
                httpUserAgent = "";
            if (httpRemoteAddress == null)
                httpRemoteAddress = "";

            if (httpReferer.Length > 299)
                httpReferer = httpReferer.Substring(0, 299);

            if (httpUserAgent.Length > 299)
                httpUserAgent = httpUserAgent.Substring(0, 299);

            session.HTTP_REFERER = httpReferer;
            session.REMOTE_ADDR = httpRemoteAddress;
            session.HTTP_USER_AGENT = httpUserAgent;

            session.SetBrowserInfo();
            session.SetRefererInfo();

            session.Save();

            return session.SessionID.ToString();
        }

        public void AssignVisitorToSession(string sessionId, string visitorId)
        {
            Session session = Session.Read(int.Parse(sessionId));

            int id;

            if (int.TryParse(visitorId, out id))
                session.VisitorID = id;

            session.Save();
        }

        public void AssignUserToSession(string sessionId, string userId)
        {
            Session session = Session.Read(int.Parse(sessionId));

            int id;

            if (int.TryParse(userId, out id))
                session.UserID = id;

            session.Save();
        }


        public T GetSessionObject<T>(string sessionId) where T:class,ISessionRecord
        {
            return (T) (ISessionRecord) Session.Read(int.Parse(sessionId));
        }

        public Type GetSessionObjectType()
        {
            return typeof(Session);
        }
    }
}
